package com.leo.nio.filechannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author du
 */
public class ScatteringAndGathering {
    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(7000));


        ByteBuffer[] buffers = new ByteBuffer[2];
        buffers[0] = ByteBuffer.allocate(5);
        buffers[1] = ByteBuffer.allocate(3);

        //阻塞式调用
        SocketChannel socketChannel = serverSocketChannel.accept();

        int msgLength = 8;
        while (true) {
            //读取数据
            int hasRead = 0;
            while (hasRead < msgLength) {
                long read = socketChannel.read(buffers);
                hasRead += read;
                System.out.println("hasRead: " + hasRead);
                //观察读取后 position 和 limit
                Arrays.asList(buffers).stream().map(buffer ->
                        "position: " + buffer.position() + " limit: " + buffer.limit())
                        .forEach(System.out::println);
            }

            //改为写模式
            Arrays.asList(buffers).forEach(buffer -> buffer.flip());
            //观察反转后的 position 和 limit
            Arrays.asList(buffers).stream().map(buffer ->
                    String.format("position: %d, limit: %d", buffer.position(), buffer.limit()))
                    .forEach(System.out::println);

            //写回客户端
            long hasWrite = 0;
            while (hasWrite < msgLength) {
                long write = socketChannel.write(buffers);
                hasWrite += write;
            }

            //buffer重置
            Arrays.asList(buffers).forEach(buffer -> buffer.clear());

            //打印读写信息
            System.out.println(String.format("hasRead: %d, hasWrite: %d, msglenght: %d", hasRead, hasWrite, msgLength));
        }
    }
}
